package bitcoin

import (
	"context"
	"encoding/json"
	"github.com/OpenBazaar/wallet-interface"
	"time"
	"io/ioutil"
	"github.com/OpenBazaar/openbazaar-go/repo"
	"path"
	"github.com/OpenBazaar/openbazaar-go/bitcoin/rpc"
)

type StatusUpdater struct {
	w   wallet.Wallet
	c   chan interface{}
	ctx context.Context
}

type walletUpdateWrapper struct {
	WalletUpdate walletUpdate `json:"walletUpdate"`
}

type walletUpdate struct {
	Height      uint32 `json:"height"`
	Unconfirmed int64  `json:"unconfirmed"`
	Confirmed   int64  `json:"confirmed"`
}

func NewStatusUpdater(w wallet.Wallet, c chan interface{}, ctx context.Context) *StatusUpdater {
	return &StatusUpdater{w, c, ctx}
}

func (s *StatusUpdater) Start() {
	t := time.NewTicker(time.Second * 15)
	for {
		select {
		case <-t.C:
			confirmed, unconfirmed, _:= GetBalance()
			height, _ := s.w.ChainTip()
			u := walletUpdate{
				Height:      height,
				Unconfirmed: unconfirmed,
				Confirmed:   confirmed,
			}
			ser, err := json.MarshalIndent(walletUpdateWrapper{u}, "", "    ")
			if err != nil {
				continue
			}
			s.c <- ser
		case <-s.ctx.Done():
			break
		}
	}
}

func GetBalance()(int64, int64, error){
	addres := "0x" + GetWalletAddress()
	confirmed, error := rpc.QueryBalance(addres, "latest")
	if error!=nil {
		return 0, 0, error
	}
	all, error := rpc.QueryBalance(addres, "pending")
	if error!=nil {
		return 0, 0, error
	}
	unconfirmed := all
	return confirmed, unconfirmed, nil
}

func UnmarshalProfile(profilejson []byte)(string,error){
	m := make(map[string]interface{})
	if err := json.Unmarshal(profilejson, &m); err != nil {
		return "string error", err
	}
	keypath:= m["Keypath"].(string)

	return keypath,nil
}
func UnmarshalUTC(UTCjson []byte)(string, error){
	m := make(map[string]interface{})
	if err := json.Unmarshal(UTCjson, &m); err != nil {
		return "string error", err
	}
	UTCaddress:= m["address"].(string)

	return UTCaddress,nil
}
func GetWalletAddress()(string){
	repoPath, err := repo.GetRepoPath(false)
	var profilepath  =  path.Join(repoPath, "root", "profile.json")
	tempprofilebyte, err := ioutil.ReadFile(profilepath)
	if err != nil {
		return ""
	}
	tempprofiledata,err := UnmarshalProfile(tempprofilebyte)
	if err != nil {
		return ""
	}
	tempUTCdata, err := ioutil.ReadFile(path.Join(repoPath, "keystore", tempprofiledata))
	if err != nil {
		return ""
	}
	tempUTCaddress, err := UnmarshalUTC(tempUTCdata)
	if err != nil {
		return ""
	}
	return tempUTCaddress
}


